import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void initEle(int[] array){
        for (int i=0;i<array.length;i++){
            this.elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap(){
        for (int parent = (usedSize-1-1)/2;parent>=0;parent--){
            siftDown(parent,usedSize);
        }
    }

    private void siftDown(int parent,int usedSize){
        int child = 2*parent+1;
        //至少有左孩子
        while (child<usedSize){
            //1.比较左右孩子最大值
            if (child+1 < usedSize && elem[child] < elem[child+1]){
                child++;
            }
            //走到这里 child一定是左右孩子最大值的下标
            if (elem[child]>elem[parent]){
                swap(elem,parent,child);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }

    private void swap(int[]array,int i,int j){
        int tmp =array[i];
        array[i] =array[j];
        array[j] = tmp;
    }
    public void offer(int val){
        if (isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child){
        int parent = (child-1)/2;
        while (parent>=0){
            if (elem[child]>elem[parent]){
                swap(elem,parent,child);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }

    public void poll(){
        if (isEmpty())return;
        swap(elem,0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
    }

    public boolean isEmpty(){
        return  usedSize ==0;
    }

    public void heapSort(){
        int end = usedSize-1;
        while (end>0){
            swap(elem,0,end);
            siftDown(0,end);
            end--;
        }
    }
}
